# coding=utf-8
import json

from django.core.exceptions import ImproperlyConfigured
from django.http import JsonResponse
from django.shortcuts import render, get_object_or_404

# Create your views here.
from django.views import View
from django.views.generic import ListView
from rest_framework import status
from rest_framework.generics import CreateAPIView, ListAPIView, GenericAPIView, DestroyAPIView, RetrieveUpdateAPIView
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, UpdateModelMixin
from rest_framework.response import Response

from common.requests import err_requests, success_requests, get_body
from dictionary.models import DictionaryType, DictionaryItem
from dictionary.serializers import CreateDictionaryTypeSerializers, DictionaryTypeSerializers, \
    EditDictionaryTypeSerializer, CreateDictionaryItemSerializers, DictionaryItemSerializers
from rest_framework.filters import OrderingFilter
from django.utils.translation import ugettext_lazy as _, ungettext


class DictionaryTypeCreateView(CreateAPIView):
    serializer_class = CreateDictionaryTypeSerializers


class DictionaryTypeListView(ListAPIView):
    """
    列表数据
    """
    serializer_class = DictionaryTypeSerializers
    filter_backends = (OrderingFilter,)
    ordering_fields = ('id', 'code', 'status')
    
    def get_queryset(self):
        name = self.kwargs.get("name")
        if name:
            return DictionaryType.objects.filter(name=name, is_launched=True)
        else:
            return DictionaryType.objects.all()


class DictionaryTypeDeleteView(DestroyAPIView):
    def get_queryset(self):
        id = self.kwargs.get("pk")
        if id:
            return DictionaryType.objects.filter(id=id)
        else:
            return None


class DictionaryTypeEditView(RetrieveUpdateAPIView):
    queryset = DictionaryType.objects.all()
    serializer_class = EditDictionaryTypeSerializer
    
    def get(self, request, *args, **kwargs):
        return self.retrieve(request)
    
    def get_object(self):
        id = self.kwargs.get("pk")
        return DictionaryType.objects.filter(id=id)[0]
    
    def put(self, request, *args, **kwargs):  # 修改
        return self.update(request)


class DictionaryTypeModelListView(GenericAPIView, ListView):
    queryset = DictionaryType.objects.all()
    serializer_class = DictionaryTypeSerializers
    template_name = 'dictionary/type_list.html'
    
    def get_dictionaryType(self):
        return DictionaryType.objects.all()
    
    def get_dictionaryType_select(self):
        id = self.kwargs.get("pk")
        if id:
            return DictionaryType.objects.filter(id=id)[0]
        else:
            return None
    
    def get_dictionaryItme(self):
        type_id = self.kwargs.get("pk")
        if type_id:
            return DictionaryItem.objects.filter(type=int(type_id)).order_by("sort")
        else:
            return None
    
    def get_extra_context(self):
        dictionaryType = self.get_dictionaryType()
        dictionaryItem = self.get_dictionaryItme()
        return {
            'hide_link': True,
            'object': dictionaryType,
            'items': dictionaryItem,
            'title': _('Dictionary Type: %s') % dictionaryType,
        }
    
    def get_object_list(self):
        dictionaryType = self.get_dictionaryType()
        dictionaryItem = self.get_dictionaryItme()
        dictionaryType_select = self.get_dictionaryType_select()
        pk = self.kwargs.get("pk")
        return {"types": dictionaryType, "items": dictionaryItem, "pk": int(pk) if str(pk).isdigit() else None, "select": dictionaryType_select}
    
    def get_queryset(self):
        self.queryset = self.get_object_list()
        return super(DictionaryTypeModelListView, self).get_queryset()


class DictionaryCreateView(View):
    # serializer_class = CreateDictionaryItemSerializers
    def post(self, request):
        body = get_body(request)
        if isinstance(body, JsonResponse):
            return body
        
        type = body.get("type")
        if type is None:
            return err_requests("500")
        try:
            dictionaryType = DictionaryType.objects.create(**type)
        except Exception as e:
            return err_requests("500")
        
        items = body.get("items")
        for item in items:
            try:
                item["type"] = dictionaryType
                dictionaryItem = DictionaryItem(**item)
                dictionaryItem.save()
            except Exception as e:
                continue
        
        return success_requests()


class DictionaryItemListView(ListAPIView):
    """
    列表数据
    """
    serializer_class = DictionaryItemSerializers
    filter_backends = (OrderingFilter,)
    ordering_fields = ('id', 'code', 'value', 'type', 'sort')
    
    def get_queryset(self):
        name = self.kwargs.get("name")
        if name:
            return DictionaryItem.objects.filter(name=name, is_launched=True)
        else:
            return DictionaryItem.objects.all()


class DictionaryItemDeleteView(DestroyAPIView):
    def get_queryset(self):
        id = self.kwargs.get("pk")
        if id:
            return DictionaryItem.objects.filter(id=id)
        else:
            return None


class DictionaryItemEditView(RetrieveUpdateAPIView):
    queryset = DictionaryItem.objects.all()
    serializer_class = EditDictionaryTypeSerializer
    
    def get(self, request, *args, **kwargs):
        return self.retrieve(request)
    
    def get_object(self):
        id = self.kwargs.get("pk")
        return DictionaryItem.objects.filter(id=id)[0]
    
    def put(self, request, *args, **kwargs):  # 修改
        return self.update(request)


class DictionaryItemModelListView(GenericAPIView, ListView):
    queryset = DictionaryItem.objects.all()
    serializer_class = DictionaryItemSerializers
    template_name = 'dictionary/type_list.html'
    
    def get_dictionaryType(self):
        return get_object_or_404(DictionaryItem, pk=self.kwargs['pk'])
    
    def get_extra_context(self):
        dictionaryType = self.get_dictionaryType()
        return {
            'hide_link': True,
            'object': dictionaryType,
            'title': _('Metadata for document: %s') % dictionaryType,
        }
    
    def get_object_list(self):
        return self.get_dictionaryType()
    
    def get_queryset(self):
        # self.queryset = self.get_object_list()
        return super(DictionaryItemModelListView, self).get_queryset()


class DictionaryDetailView(View):
    def post(self, request):
        body = get_body(request)
        if isinstance(body, JsonResponse):
            return body
        type_id = body.get("id")
        if type_id is None:
            return err_requests("500")
        type = DictionaryType.objects.filter(id=type_id).values()[0]
        items = list(DictionaryItem.objects.filter(type=type_id).values("sort", "code", "name", "id", "value"))
        try:
            json.dumps({
                "type": type,
                "items": items
            })
            data = {
                "type": type,
                "items": items
            }
            return success_requests(data)
        except Exception as e:
            return err_requests("500")


class DictionaryEditView(View):
    def post(self, request):
        body = get_body(request)
        if isinstance(body, JsonResponse):
            return body
        type = body.get("type")
        if type is None:
            return err_requests("500")
        try:
            type_id = type["id"]
            type = DictionaryType.objects.filter(id=type_id).update(**type)
        except Exception as e:
            return err_requests("500")
        
        items = body.get("items")
        old_items = DictionaryItem.objects.filter(type=type_id)
        try:
            old_items.delete()
        except Exception as e:
            pass
        
        for item in items:
            try:
                item["type"] = DictionaryType.objects.get(id=type_id)
                item = DictionaryItem.objects.create(**item)
            except Exception as e:
                print e
                continue

        return success_requests()


class DictionaryDeleteView(View):
    def post(self, request):
        body = get_body(request)
        if isinstance(body, JsonResponse):
            return body
        type = body.get("type")
        if type is None:
            return err_requests("500")
        try:
            type_id = type["id"]
            DictionaryType.objects.filter(id=type_id).update(**type)
        except Exception as e:
            return err_requests("500")
        
        try:
            DictionaryItem.objects.filter(type=type_id).delete()
        except Exception as e:
            return err_requests("500")
        
        try:
            DictionaryType.objects.filter(id=type_id).delete()
        except Exception as e:
            return err_requests("500")
        return success_requests()
